import 'dart:developer' as developer;
import 'dart:io' show Platform;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';

// 导入桌面窗口管理包
import 'package:window_manager/window_manager.dart';

// 导入数据库相关包
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:provider/provider.dart';

import 'app/services/database_service.dart';
import 'app/navigation/app_router.dart';
import 'app/app.dart';
import 'app/providers/theme_provider.dart';
import 'app/providers/font_size_provider.dart';
import 'app/utils/custom_keyboard_handler.dart';



void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 根据平台选择合适的数据库初始化方式
  if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
    // 桌面平台使用sqflite_ffi
    sqfliteFfiInit();
    databaseFactory = databaseFactoryFfi;
    developer.log('Main: 初始化sqflite_ffi完成（桌面平台）');
  } else {
    // 移动平台或Web平台使用默认的sqflite
    developer.log('Main: 使用默认sqflite（移动平台或Web平台）');
  }
  
  
  // 桌面平台窗口设置
  if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
    await windowManager.ensureInitialized();
    
    WindowOptions windowOptions = const WindowOptions(
      size: Size(1024, 768),
      center: true,
      backgroundColor: Colors.white,
      skipTaskbar: false,
      titleBarStyle: TitleBarStyle.normal,
      title: '学习宝库',
      minimumSize: Size(800, 600),
    );
    
    windowManager.waitUntilReadyToShow(windowOptions, () async {
      await windowManager.show();
      await windowManager.focus();
    });
    
    developer.log('Main: 桌面窗口初始化完成');
  }
  
  try {
    developer.log('Main: 开始初始化数据库');
    final databaseService = DatabaseService();
    await databaseService.initDatabase();
    developer.log('Main: 数据库初始化成功');
  } catch (e) {
    developer.log('Main: 数据库初始化失败: $e', error: e);
  }
  
  // 初始化自定义键盘处理器
  if (!kIsWeb && Platform.isWindows) {
    try {
      await CustomKeyboardHandler.instance.initialize();
      developer.log('Main: 自定义键盘处理器初始化成功');
    } catch (e) {
      developer.log('Main: 自定义键盘处理器初始化失败: $e', error: e);
    }
  }
  
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => ThemeProvider()),
        ChangeNotifierProvider(create: (_) => FontSizeProvider()),
      ],
      child: const StudyTreasureApp(),
    );
  }

}